import logging

from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.web.models import PagingUtil
from app.web.models.Database import get_db
from app.web.models.JobSeeker import Resume, JobSeeker
from app.web.models.Recruiter import Recruiter, JobPost, JobPostResume, ResumeReport
from app.web.routers.Schemas import JobPostSchema, PaginationSchema, ApplicantSchema

logger = logging.getLogger(__name__)
router = APIRouter()


@router.post("/saveJobPost")
async def save_job_post(job_post_schema: JobPostSchema, db: Session = Depends(get_db)):
    recruiter = db.query(Recruiter).get(job_post_schema.recruiter_id)
    if recruiter is None:
        raise Exception(f"找不到对应的招聘员{job_post_schema.recruiter_id}")
    if job_post_schema.id is None:
        job_post = JobPost()
        job_post.__dict__.update(vars(job_post_schema))
        db.add(job_post)
        db.commit()
        db.refresh(job_post)
        job_post_schema.id = job_post.id
        job_post_schema.publish_date = job_post.publish_date.strftime("%Y-%m-%d %H:%M:%S")
        return job_post_schema
    else:
        job_post = db.query(JobPost).get(job_post_schema.id)
        print(f"JobPost: {job_post}")
        if job_post.recruiter_id == job_post_schema.recruiter_id:
            job_post.title = job_post_schema.title
            job_post.company = job_post_schema.company
            job_post.location = job_post_schema.location
            job_post.salary = job_post_schema.salary
            job_post.requirements = job_post_schema.requirements
            job_post.description = job_post_schema.description
            db.commit()
            return job_post_schema
        else:
            raise Exception(f"找不到招聘员{job_post_schema.recruiter_id}编辑的岗位{job_post_schema.id}")


@router.get("/getJobPages")
async def get_job_pages(recruiter_id: int = Query(None), page: int = Query(0), rows_per_page: int = Query(10),
                        db: Session = Depends(get_db)):
    logger.info(f"recruiter_id: {recruiter_id}, page: {page}, rows_per_page: {rows_per_page}")
    job_post_list, total = PagingUtil.paginate(db.query(JobPost).filter(JobPost.recruiter_id == recruiter_id),
                                               page=page, rows_per_page=rows_per_page)
    results = []
    for job_post in job_post_list:
        job_post_schema = JobPostSchema(
            id=job_post.id, recruiter_id=job_post.recruiter_id, title=job_post.title,
            company=job_post.company, location=job_post.location, salary=job_post.salary,
            description=job_post.description, requirements=job_post.requirements,
            publish_date=job_post.publish_date.strftime("%Y-%m-%d %H:%M:%S")
        )
        results.append(job_post_schema)
    return PaginationSchema(page=page, rowsPerPage=rows_per_page, data=results, rowsNumber=total)


@router.get("/getApplicantList")
async def get_applicant_list(recruiter_id: int = Query(None), job_post_id: int = Query(None),
                             page: int = Query(0), rows_per_page: int = Query(10),
                             db: Session = Depends(get_db)):
    job_post: JobPost = db.query(JobPost).get(job_post_id)
    if job_post is None or job_post.recruiter_id != recruiter_id:
        raise Exception("找不到对应的岗位")
    stmt = select(ResumeReport.id, ResumeReport.match_rate, ResumeReport.description, ResumeReport.status,
                  JobSeeker.id, JobSeeker.name, Resume.id, Resume.file_name) \
        .select_from(JobPostResume).where(JobPostResume.job_post == job_post_id) \
        .join(Resume, Resume.id == JobPostResume.resume) \
        .join(ResumeReport, ResumeReport.job_post_resume == JobPostResume.id) \
        .join(JobSeeker, JobSeeker.id == Resume.job_seeker)
    results, total = PagingUtil.paginate_select(stmt, page=page, rows_per_page=rows_per_page, db=db)
    applicants = []
    for row in results:
        print(row)
        report_id: int = row[0]
        match_rate: float = row[1]
        description: str = row[2]
        status: str = row[3]
        job_seeker_id: int = row[4]
        job_seeker_name: str = row[5]
        resume_id: int = row[6]
        resume_name: str = row[7]
        applicant = ApplicantSchema(
            report_id=report_id, match_rate=match_rate, description=description, status=status,
            job_seeker_id=job_seeker_id, job_seeker_name=job_seeker_name,
            resume_id=resume_id, resume_name=resume_name, job_post_id=job_post_id)
        applicants.append(applicant)
    pagination = PaginationSchema(page=page, rowsPerPage=rows_per_page, rowsNumber=total, data=applicants)
    return pagination


@router.get("/allJobs")
async def get_all_jobs(db: Session = Depends(get_db)):
    return db.query(JobPost).all()


@router.get("/testUser")
async def get_test_user(db: Session = Depends(get_db)):
    return db.query(Recruiter).first()
